import 'dart:async';
import 'dart:convert';

import 'package:animated_digit/animated_digit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/pages/games/allGame/dice/slider_shape.dart';
import 'package:spree/pages/games/games_auto.dart';
import 'package:spree/utils/account.dart';
import 'package:spree/utils/utils.dart';
import 'package:spree/utils/videoUtil.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:spree/widgets/vip_rectangle_box.dart';
import 'package:zflutter/zflutter.dart';
import 'dart:math';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import '../../../../provider/model/user_model.dart';
import '../../../../utils/api.dart';
import '../../../../utils/precision_limit_formatter.dart';
import '../../game_title_bar.dart';

class DicePage extends StatefulWidget {
  DicePage({Key? key}) : super(key: key);

  @override
  State<DicePage> createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> with TickerProviderStateMixin {
  late TabController _tabController;
  late TabController _tabController2;
  List _tabs = ["Manual", "Auto"];
  List _tabs2 = ["My Bets", "Player List"];
  int _fIndex = 0;
  int _fIndex2 = 0;
  late AnimatedDigitController _accountAmountController;

  late AnimationController animationController =
      AnimationController(vsync: this, duration: Duration(milliseconds: 2000));
  late Animation animation =
      Tween(begin: 0.0, end: 1.0).animate(animationController);
  final IO.Socket _socket = IO.io(
      'http://47.95.0.143:9005',
      IO.OptionBuilder()
          .setPath('/game/socket.io')
          .setTransports(['websocket'])
          .disableAutoConnect()
          .build());
  bool _isRollUnder = true;
  int _sliderValue = 49;
  String _rollNumber = '0';
  List<Widget> _rollNumberList = [];
  late TextEditingController _textEditingController;
  int _minButtonSelect = 0;
  bool _inAnimation = false;
  double _money = 0;
  // 表头
  List<String> _myBetHeader = ['Bet ID', 'Time', 'Bet', 'Cash Out', 'Profit'];
  List<String> _playerHeader = ['Player', 'Cash Out', 'Bets'];
  // 数据
  List<Map> _myBetData = [];
  List<Map> _playerData = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _tabController2 = TabController(length: _tabs2.length, vsync: this);
    _textEditingController = TextEditingController(text: '1');
    animationController.repeat(reverse: true);
    animation.addListener(() {
      setState(() {});
    });
    wsConnect(context);
    String accountAmount = context.read<UserModel>().accountAmount;
    if (accountAmount != '') {
      _accountAmountController =
          AnimatedDigitController(double.parse(accountAmount));
    } else {
      _accountAmountController = AnimatedDigitController(0.00);
    }
    setState(() {});
    getMyBetsAndAccount();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    animationController.dispose();
    _tabController.dispose();
    _tabController2.dispose();
    _textEditingController.dispose();
    if (_socket != null) {
      _socket.clearListeners();
      _socket.disconnect();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SvgPicture.asset('images/BETSPREELOGO.svg'),
            Consumer<UserModel>(builder: (context, value, child) {
              return _circleMoney();
            })
          ],
        ),
      ),
      body: Consumer<UserModel>(builder: (context, value, child) {
        return CommonContainer(
          child: ListView(
            children: [
              GameTitleBar(
                gameName: 'Dice',
                ontap: (type) {
                  if (type == 'info') {
                    Navigator.pushNamed(context, 'DiceRules');
                  }
                },
              ),
              Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Utils().createMaterialColor(),
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  boxShadow: [
                    BoxShadow(
                        color: Color(0xFF261E54),
                        offset: Offset(0.0, 1.0),
                        blurRadius: 1,
                        spreadRadius: 2)
                  ],
                ),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: _rollNumberList,
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10, bottom: 10),
                      decoration: BoxDecoration(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(8.0)),
                          gradient: LinearGradient(
                            colors: [
                              Color.fromRGBO(26, 19, 65, 0),
                              _isRollUnder
                                  ? Color.fromRGBO(76, 46, 255, 1)
                                  : Color(0xFFFF3F61)
                            ],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                          )),
                      child: Padding(
                        padding: EdgeInsets.only(
                            top: 20, bottom: 20, left: 20, right: 20),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Column(
                              children: [
                                Text(
                                  '$_sliderValue',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 28,
                                      fontWeight: FontWeight.w800),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(top: 8),
                                  child: Text(
                                    'Prediction',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12,
                                        fontWeight: FontWeight.w800),
                                  ),
                                )
                              ],
                            ),
                            Expanded(
                              flex: 1,
                              child: Center(
                                child: Container(
                                  width: 100,
                                  height: 100,
                                  child: ZDragDetector(
                                      builder: (context, controller) {
                                    return ZIllustration(
                                      zoom: 1,
                                      children: [
                                        ZPositioned(
                                          rotate: controller.rotate,
                                          child: ZPositioned(
                                            translate: ZVector.only(x: 0),
                                            child: ZGroup(
                                              children: [
                                                ..._renderDialect(),
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    );
                                  }),
                                ),
                              ),
                            ),
                            Column(
                              children: [
                                Text(
                                  '$_rollNumber',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 28,
                                      fontWeight: FontWeight.w800),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(top: 8),
                                  child: Text(
                                    'Lucky Number',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12,
                                        fontWeight: FontWeight.w800),
                                  ),
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _colorContainer(
                            text: 'Roll Under',
                            onClick: () {
                              setState(() {
                                if (_sliderValue > 95) {
                                  _sliderValue = 95;
                                }
                                _isRollUnder = true;
                                // _linearColor = Color.fromRGBO(76, 46, 255, 1);
                              });
                            }),
                        _colorContainer(
                            text: 'Roll Over',
                            color: Color(0xFFFF3F61),
                            onClick: () {
                              setState(() {
                                _isRollUnder = false;
                                // _linearColor = Color(0xFFFF3F61);
                              });
                            }),
                      ],
                    ),
                    SliderTheme(
                      data: SliderTheme.of(context)
                          .copyWith(thumbShape: SquareSliderComponentShape()),
                      child: Slider(
                          value: double.parse('$_sliderValue'),
                          max: _isRollUnder ? 95 : 98,
                          min: 1,
                          divisions: _isRollUnder ? 95 : 98,
                          label: _sliderValue.round().toString(),
                          activeColor: Color(0xFF5484FF),
                          inactiveColor: Color(0xFFFF3F61),
                          onChanged: (value) {
                            setState(() {
                              _sliderValue = int.parse('${value.round()}');
                            });
                          }),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 20),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 80,
                        // alignment: Alignment.center,
                        padding: EdgeInsets.only(
                            left: 10, right: 10, top: 4, bottom: 4),
                        decoration: BoxDecoration(
                          border: _loutLine(),
                          borderRadius:
                              const BorderRadius.all(Radius.circular(10.0)),
                        ),
                        child: Row(
                          children: [
                            Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                _minButton(
                                    onTap: () {
                                      _textEditingController.text = '0';
                                      setState(() {
                                        _minButtonSelect = 1;
                                      });
                                    },
                                    isSelect: _minButtonSelect == 1,
                                    child: Text(
                                      'Min',
                                      style: TextStyle(color: Colors.white),
                                    )),
                                _minButton(
                                    onTap: () {
                                      _textEditingController.text = '1000';
                                      setState(() {
                                        _minButtonSelect = 2;
                                      });
                                    },
                                    isSelect: _minButtonSelect == 2,
                                    child: Text(
                                      'Max',
                                      style: TextStyle(color: Colors.white),
                                    ))
                              ],
                            ),
                            Expanded(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    'R\$',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.w800),
                                  ),
                                  TextField(
                                    controller: _textEditingController,
                                    textAlign: TextAlign.center,
                                    style: TextStyle(color: Colors.white),
                                    keyboardType: TextInputType.number,
                                    inputFormatters: [
                                      // FilteringTextInputFormatter.allow(
                                      //     RegExp("[0-9]"))
                                      PrecisionLimitFormatter(2)
                                    ],
                                    cursorColor: Colors.white,
                                    decoration: InputDecoration(
                                      border: InputBorder.none,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                _minButton(
                                    onTap: () {
                                      setState(() {
                                        _minButtonSelect = 3;
                                      });
                                      try {
                                        _textEditingController.text =
                                            '${double.parse(_textEditingController.text) ~/ 2}';
                                      } catch (e) {}
                                    },
                                    isSelect: _minButtonSelect == 3,
                                    child: Text(
                                      '1/2',
                                      style: TextStyle(color: Colors.white),
                                    )),
                                _minButton(
                                    onTap: () {
                                      setState(() {
                                        _minButtonSelect = 4;
                                      });
                                      try {
                                        _textEditingController.text =
                                            '${double.parse(_textEditingController.text) * 2}';
                                      } catch (e) {}
                                    },
                                    isSelect: _minButtonSelect == 4,
                                    child: Text(
                                      '2x',
                                      style: TextStyle(color: Colors.white),
                                    ))
                              ],
                            ),
                          ],
                        ),
                      ),
                      flex: 6,
                    ),
                    Expanded(
                      flex: 4,
                      child: GestureDetector(
                        onTap: () {
                          // animationController.stop();
                          // animationController.duration =
                          //     const Duration(milliseconds: 250);
                          // animationController.repeat(reverse: true);

                          // Future.delayed(Duration(milliseconds: 2000), (() {
                          //   animationController.stop();
                          //   animationController.duration =
                          //       const Duration(milliseconds: 3000);
                          //   animationController.repeat(reverse: true);
                          // }));
                        },
                        child: GestureDetector(
                          onTap: () async {
                            if (value.userId == '') {
                              Navigator.pushNamed(context, 'LoginPage')
                                  .then((user) {
                                if (mounted) {
                                  wsConnect(context);
                                }

                                Map pre = {'userId': user, 'gameType': 'DICE'};
                                sendMsg('game_pre', pre);
                              });
                              return;
                            }

                            if (_textEditingController.text == '' ||
                                int.parse(_textEditingController.text) == 0) {
                              EasyLoading.showToast('please type in amount');
                              return;
                            }
                            order(value.userId);
                          },
                          child: Container(
                            height: 80,
                            alignment: Alignment.center,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  'BET',
                                  style: TextStyle(
                                      color: Utils().whiteColor(),
                                      fontSize: 20),
                                ),
                                // Visibility(
                                //     visible: true,
                                //     child: Text(
                                //       '这里填写倍数',
                                //       style: TextStyle(
                                //           color: Utils().whiteColor(),
                                //           fontSize: 12),
                                //     ))
                              ],
                            ),
                            margin: EdgeInsets.only(left: 10),
                            decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0)),
                              color: Color(0xFF7A50F0),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              TabBar(
                controller: _tabController,
                tabs: _tabs.map((e) => Tab(text: e)).toList(),
                onTap: (i) {
                  setState(() {
                    _fIndex = i;
                  });
                },
              ),
              _fIndex == 1 ? GamesAuto() : Container(),
              TabBar(
                indicator: const UnderlineTabIndicator(
                    borderSide: BorderSide(width: 2.0, color: Colors.red)),
                controller: _tabController2,
                tabs: _tabs2.map((e) => Tab(text: e)).toList(),
                onTap: (i) {
                  setState(() {
                    _fIndex2 = i;
                  });
                },
              ),
              VipRectangleBox(
                color: Color(0xFF291F62),
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: _tableList(_fIndex2),
                ),
              ),
            ],
          ),
        );
      }),
    );
  }

  Widget _numberButton(
      {String? number,
      double? width = 30,
      double? height = 20,
      Color? textColor}) {
    return Container(
      width: width,
      height: height,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: Color(0xFF433A79),
          borderRadius: BorderRadius.all(Radius.circular(5.0))),
      child: Text(
        number ?? '',
        style: TextStyle(color: textColor ?? Color(0xFF5484FF)),
      ),
    );
  }

  _colorContainer(
      {double? width = 150,
      double? height = 50,
      Color? color,
      String? text,
      Function? onClick}) {
    return GestureDetector(
      onTap: () {
        if (onClick != null) {
          onClick();
        }
      },
      child: Container(
        alignment: Alignment.center,
        width: width,
        height: height,
        decoration: BoxDecoration(
            color: color ?? Color(0xFF5484FF),
            borderRadius: BorderRadius.all(Radius.circular(5.0))),
        child: Text(
          text ?? '',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  // 边框的container
  Border _loutLine() {
    return Border.all(width: 1, color: Color.fromRGBO(255, 255, 255, 0.5));
  }

  Widget _minButton(
      {Widget? child, EdgeInsets? margin, Function? onTap, bool? isSelect}) {
    return GestureDetector(
      onTap: () {
        if (onTap != null) {
          onTap();
        }
      },
      child: Container(
        margin: margin,
        decoration: BoxDecoration(
          color: isSelect == true ? Color(0xFF7A50F0) : Color(0xFF413497),
          borderRadius: const BorderRadius.all(Radius.circular(4.0)),
        ),
        padding: EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
        child: child,
      ),
    );
  }

  Widget _dot({double size = 30, EdgeInsets? margin}) {
    return Container(
      width: size,
      height: size,
      margin: margin,
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.all(Radius.circular(size / 2)),
      ),
    );
  }

  // 骰子点
  Widget _dialectDot(int dot) {
    const double size = 10;
    Widget one = Align(alignment: Alignment.center, child: _dot(size: 20));
    Widget tow = Align(
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _dot(size: size),
          _dot(size: size, margin: EdgeInsets.only(left: 4))
        ],
      ),
    );
    Widget three = Align(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size),
                _dot(size: size, margin: EdgeInsets.only(left: 4))
              ],
            ),
          ],
        ));
    Widget four = Align(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
                _dot(size: size, margin: EdgeInsets.only(left: 4, bottom: 4))
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size),
                _dot(size: size, margin: EdgeInsets.only(left: 4))
              ],
            ),
          ],
        ));
    Widget five = Align(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
                _dot(size: size, margin: EdgeInsets.only(left: 12, bottom: 4))
              ],
            ),
            _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size),
                _dot(size: size, margin: EdgeInsets.only(left: 12))
              ],
            ),
          ],
        ));
    Widget six = Align(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
                _dot(size: size, margin: EdgeInsets.only(left: 4, bottom: 4))
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size, margin: EdgeInsets.only(bottom: 4)),
                _dot(size: size, margin: EdgeInsets.only(left: 4, bottom: 4))
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _dot(size: size),
                _dot(size: size, margin: EdgeInsets.only(left: 4))
              ],
            ),
          ],
        ));
    if (dot == 1) {
      return one;
    }
    if (dot == 2) {
      return tow;
    }
    if (dot == 3) {
      return three;
    }
    if (dot == 4) {
      return four;
    }
    if (dot == 5) {
      return five;
    }
    if (dot == 6) {
      return six;
    }
    return one;
  }

  // 骰子
  _renderDialect() {
    return [
      ZPositioned(
        rotate: ZVector.only(z: pi * animation.value, x: pi * animation.value),
        child: ZPositioned(
          translate: ZVector(0, 0, 0),
          child: ZBoxToBoxAdapter(
            height: 60,
            width: 60,
            depth: 60,
            color: Colors.red,
            front: Container(
              color: Color(0xFFEFEFEF),
              alignment: Alignment.center,
              child: _dialectDot(1),
            ),
            top: Container(
              color: Color(0xFFD9D9D9),
              child: _dialectDot(2),
            ),
            right: Container(
              color: Colors.white,
              child: _dialectDot(3),
            ),
            left: Container(
              color: Colors.white,
              child: _dialectDot(4),
            ),
            bottom: Container(
              color: Color(0xFFD9D9D9),
              child: _dialectDot(5),
            ),
            rear: Container(
              color: Color(0xFFEFEFEF),
              child: _dialectDot(6),
            ),
          ),
        ),
      ),
    ];
  }

// 初始化ws
  wsConnect(BuildContext context) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String? accessToken = context.read<UserModel>().accessToken;
      String? userId = context.read<UserModel>().userId;
      if (userId == '') {
        return;
      }
      _socket.connect();
      _socket.onConnect((data) async {
        if (userId != '') {
          Map pre = {'userId': userId, 'gameType': 'DICE'};
          sendMsg('game_pre', pre);
        }

        _onMessage(userId);
      });
      _socket.onDisconnect((data) {
        print('断开=====');
      });

      // _onMessage(context);
    } catch (e) {
      print(e);
    }
  }

  // 监听消息
  _onMessage(String? userId) {
    try {
      _socket.on('game_pre', (data) {});
      _socket.on('game_start', (data) async {
        Map result = jsonDecode(data);
        if (!result['success']) {
          _showChargeAlert(result['errorMsg']);
          return;
        }
        startAnimation();
        Future.delayed(const Duration(milliseconds: 1000), showResult(result));

        Map pre = {'userId': userId, 'gameType': 'DICE'};
        sendMsg('game_pre', pre);
        getMyBets();
      });
      _socket.on("game_real_time_dice", ((data) {
        List result = jsonDecode(data);
        _playerData = [];
        if (result.length > 0) {
          for (int i = 0; i < result.length; i++) {
            _playerData.add({
              'player': result[i]['userName'],
              'cashOut': result[i]['mutiplier'].toString() + 'x',
              'bets': result[i]['betAmount'],
              'win': result[i]['win']
            });
          }
        }
      }));
    } catch (e) {
      print(e);
    }
  }

  // 发送消息
  sendMsg(msg, prama) {
    print(prama);
    try {
      _socket.emit(msg, prama);
    } catch (e) {}
  }

  // 断开连接
  disConnect() {
    try {
      _socket.onDisconnect((data) {});
    } catch (e) {}
  }

  // 开始动画
  Future _startAnimation() {
    animationController.stop();
    animationController.duration = const Duration(milliseconds: 250);
    animationController.repeat(reverse: true);
    return Future.delayed(Duration(milliseconds: 1000), (() {
      animationController.stop();
      animationController.duration = const Duration(milliseconds: 2000);
      animationController.repeat(reverse: true);
    }));
  }

  // 显示弹出层
  _showDialog(bool isLose, {String? title, String? subTitle}) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 250,
                height: 100,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                    gradient: LinearGradient(
                      colors: [
                        isLose ? Color(0xFFFF3F61) : Color(0xFFB275FF),
                        isLose ? Color(0xFFFF855F) : Color(0xFF5F82FF),
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    )),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      title ?? '',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                          fontWeight: FontWeight.w700),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Text(
                        subTitle ?? '',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  ],
                ),
              )
            ],
          );
        });
    Future.delayed(Duration(seconds: 1), () {
      Navigator.of(context).pop();
    });
  }

  Widget _tableList(index) {
    if (index == 1) {
      return DataTable(
        columns: _playerHeader.map((e) {
          return DataColumn(
            label: Text(
              '$e',
              style: TextStyle(color: Colors.white38),
            ),
          );
        }).toList(),
        rows: _createTableRow(_playerData, ['player', 'cashOut', 'bets']),
      );
    }
    return DataTable(
      columns: _myBetHeader.map((e) {
        return DataColumn(
          label: Text(
            '$e',
            style: TextStyle(color: Colors.white38),
          ),
        );
      }).toList(),
      rows: _createTableRow(
          _myBetData, ['betId', 'time', 'bet', 'cashOut', 'profit']),
    );
  }

  List<DataRow> _createTableRow(List<Map> data, List<String> keys) {
    return data.map((e) => DataRow(cells: _createTableCell(e, keys))).toList();
  }

  getMyBets() async {
    //当前时间倒推1个月
    var now = DateTime.now();
    DateTime newMonth = DateTime(now.year, now.month - 1, now.day);
    String endDate = DateFormat("yyyy-MM-dd").format(now);
    String startDate = DateFormat("yyyy-MM-dd").format(newMonth);

    Map param = {
      'gameType': 'DICE',
      'startDate': startDate,
      'endDate': endDate,
      'limit': 20,
      'pageSize': 10
    };
    try {
      dynamic result = await Api.historyInfo(param);
      List tempData = result['data'];
      _myBetData = [];
      if (tempData.length > 0) {
        for (int i = 0; i < tempData.length; i++) {
          _myBetData.add({
            'betId': tempData[i]['recordNo'],
            'time': tempData[i]['playTime'],
            'bet': tempData[i]['betAmount'],
            'cashOut': tempData[i]['payOut'].toStringAsFixed(2) + 'x',
            'profit': tempData[i]['winAmount'].toStringAsFixed(2)
          });
        }
      }
    } catch (e) {}
  }

  _showChargeAlert(String msg) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Tips"),
            content: Text("$msg"),
            actions: <Widget>[
              TextButton(
                child: Text("Cancel"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              TextButton(
                child: Text("Deposit"),
                onPressed: () {
                  // 跳转到充值页面
                  //需要销毁当前
                  Navigator.pushNamed(context, 'DepositPage');
                  // Navigator.of(context).pop(true); //关闭对话框
                },
              ),
            ],
          );
        });
  }

  List<DataCell> _createTableCell(Map data, List<String> keys) {
    return keys.map((e) {
      if (['bet', 'profit', 'bets'].contains(e)) {
        return DataCell(
          Row(
            children: [
              Text(
                'R\$ ',
                style: TextStyle(color: Color(0xFFFFED4A)),
              ),
              Text(
                '${data[e]}',
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        );
      }
      if (['cashOut', 'result'].contains(e)) {
        if (e == 'cashOut') {
          Color color = Colors.green;
          if (data['profit'] == '0.00' || data['win'] == false) {
            color = Colors.red;
          }
          return DataCell(
            Container(
              width: 50,
              height: 20,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.all(Radius.circular(3.0)),
              ),
              alignment: Alignment.center,
              child: Text(
                '${data[e]}',
                style: TextStyle(color: Colors.white),
              ),
            ),
          );
        }
      }
      return DataCell(Text(
        '${data[e]}',
        style: TextStyle(color: Colors.white60),
      ));
    }).toList();
  }

  getMyBetsAndAccount() {
    String? userId = context.read<UserModel>().userId;
    if (userId != '') {
      getMyBets();
      Future.delayed(Duration(milliseconds: 200), (() {
        Account.refreshAccount(context);
      }));
    }

    String accountAmount = context.read<UserModel>().accountAmount;
    if (accountAmount != '') {
      _accountAmountController.value = double.parse(accountAmount);
    }
    setState(() {});
  }

  order(userId) {
    Map message = {
      'userId': userId,
      'gameType': 'DICE',
      'amount': int.parse(_textEditingController.text),
      'isUnder': _isRollUnder ? 1 : 2,
      'isfast': false,
      'prediction': _sliderValue
    };
    sendMsg("game_start", message);
  }

  startAnimation() {
    VideoUtil.playVideoByUrl("sounds/dice/dice-place-bet.mp3");
    _startAnimation();
  }

  showResult(result) {
    if (mounted) {
      Container w = Container(
        margin: EdgeInsets.only(left: 4),
        child: _numberButton(
            number: '${result['rollNumber']}',
            textColor: double.parse('${result['winAmount']}') == 0
                ? Colors.red
                : null),
      );
      setState(() {
        _rollNumber = '${result['rollNumber']}';

        _rollNumberList.add(w);
        if (_rollNumberList.length >= 8) {
          _rollNumberList.removeAt(0);
        }
      });
      double inputMoney = double.parse(_textEditingController.text);
      if (double.parse('${result['winAmount']}') == 0) {
        _accountAmountController.addValue(-inputMoney);
        _showDialog(true,
            title: 'You Lose', subTitle: _textEditingController.text + "x");
        VideoUtil.playVideoByUrl("sounds/dice/dice-lose.mp3");
      } else {
        _accountAmountController
            .addValue(double.parse('${result['winAmount']}'));
        _showDialog(false,
            title: 'You Won',
            subTitle: 'R\$' + result['winAmount'].toStringAsFixed(2));
        VideoUtil.playVideoByUrl("sounds/dice/dice-win.mp3");
      }
    }
  }

  _circleMoney({double? width}) {
    return Row(
      children: [
        Container(
          width: width,
          margin: EdgeInsets.only(left: 12),
          padding: EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              border: Border.all(color: Color(0xFF9C4EFF), width: 1)),
          child: Row(
            children: [
              Container(
                width: 24,
                height: 24,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xFF9174FB),
                    borderRadius: BorderRadius.all(Radius.circular(12.0))),
                child: Text(
                  "R\$",
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.white,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 5),
                child: AnimatedDigitWidget(
                  value: _accountAmountController.value,
                  textStyle: TextStyle(color: Colors.white, fontSize: 10),
                  fractionDigits: 2,
                  enableDigitSplit: true,
                  digitSplitSymbol: ",",
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 20),
          child: GestureDetector(
            onTap: (){
              Navigator.pushNamed(context, 'WithdrawnPage');
            },
            child: Image.asset(
            'images/wallet-app-bar.png',
            width: 24,
          ),
          ),
        )
      ],
    );
  }
}
